/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package JFreeChartExtensions.Fitters;

import JFreeChartExtensions.Series.XYExtendedIntervalSeries;
import JFreeChartExtensions.Series.XYRegressionSeries;
import java.io.Serializable;
import org.apache.commons.math.optimization.OptimizationException;

/**
 *
 * @author Nobody
 */
public class ChartFit implements Serializable{

    private Double xStart = null;
    private Double xEnd = null;

    public ChartFit(Double xStart, Double xEnd) {
        this.xStart = xStart;
        this.xEnd = xEnd;
    }

    public ChartFit() {
    }

    public XYExtendedIntervalSeries regress(XYExtendedIntervalSeries series, IReggression reggression) throws OptimizationException {
        if (areBoundsDefined()) {
            return regress(series, xStart, xEnd, reggression);
        }
        return reggression.regress(series);
    }

    public XYExtendedIntervalSeries regress(XYExtendedIntervalSeries series, double xStart, double xEnd, IReggression reggression) throws OptimizationException {

        XYExtendedIntervalSeries subSeries = new XYRegressionSeries((Comparable)(series.getKey() + " " + reggression.toString()));

        for (int i = 0; i < series.getItemCount(); ++i) {
            if ((Double) series.getX(i) > getxStart() && (Double) series.getX(i) < getxEnd()) {
                subSeries.add(((Double)series.getX(i)).doubleValue(),
                        series.getXLowValue(i),
                        series.getXHighValue(i),
                        series.getYValue(i),
                        series.getXLowValue(i),
                        series.getXHighValue(i));
            }
        }

        XYRegressionSeries regressionSeries = reggression.regress(subSeries);
        regressionSeries.setIsRegressionSeries(true);
        return regressionSeries;
    }

    public boolean isXStartDefined() {
        return xStart != null;
    }

    public boolean isXEndDefined() {
        return xEnd != null;
    }

    public boolean areBoundsDefined() {
        return isXStartDefined() && isXEndDefined();
    }

    public Double getxEnd() {
        return xEnd;
    }

    public void setxEnd(Double xEnd) {
        this.xEnd = xEnd;
    }

    public void sortBounds() {
        if (xStart > xEnd) {
            double temp;
            temp = xStart;
            xStart = xEnd;
            xEnd = temp;
        }

    }

    public Double getxStart() {
        return xStart;
    }

    public void setxStart(Double xStart) {
        this.xStart = xStart;
    }

    public void reset() {
        xStart = null;
        xEnd = null;
    }
}
